﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService.TransportHandle
// 文 件 名：	PacketFileCheck
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2018/6/19 15:08:00
//========================================
using System;
using System.Linq;

namespace SFJDService.TransportHandle
{
    public struct PacketFileCheck
    {
        public const int Length = 9;
        /// <summary>
        /// 校验结果
        /// </summary>
        public bool Boolean { set; get; }
        /// <summary>
        /// 文件序列号
        /// </summary>
        public int FileIndex { set; get; }
        /// <summary>
        /// 字节序列号
        /// </summary>
        public int ByteIndex { set; get; }

        public PacketFileCheck(bool boo, int fileIndex, int byteIndex)
        {
            Boolean = boo;
            FileIndex = fileIndex;
            ByteIndex = byteIndex;
        }

        public PacketFileCheck(byte[] bytes)
        {
            Boolean = BitConverter.ToBoolean(bytes, 0);
            FileIndex = BitConverter.ToInt32(bytes.Skip(1).Take(4).ToArray(), 0);
            ByteIndex = BitConverter.ToInt32(bytes.Skip(5).Take(4).ToArray(), 0);
        }

        public  byte[] ToBytes()
        {
            byte[] b = new byte[9];
            Buffer.BlockCopy(BitConverter.GetBytes(Boolean), 0, b, 0, 1);
            Buffer.BlockCopy(BitConverter.GetBytes(FileIndex), 0, b, 1, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(ByteIndex), 0, b, 5, 4);
            return b;
        }

        public override bool Equals(object obj)
        {
            if (!(obj is PacketFileCheck))
            {
                return false;
            }

            var check = (PacketFileCheck)obj;
            return Boolean == check.Boolean &&
                   FileIndex == check.FileIndex &&
                   ByteIndex == check.ByteIndex;
        }

        public override int GetHashCode()
        {
            var hashCode = 276132245;
            hashCode = hashCode * -1521134295 + base.GetHashCode();
            hashCode = hashCode * -1521134295 + Boolean.GetHashCode();
            hashCode = hashCode * -1521134295 + FileIndex.GetHashCode();
            hashCode = hashCode * -1521134295 + ByteIndex.GetHashCode();
            return hashCode;
        }

        public override string ToString()
        {
            return Boolean + ": " + ByteIndex + "/" + FileIndex;
        }

        public static bool operator ==(PacketFileCheck left, PacketFileCheck right)
        {
            if (ReferenceEquals(left, right))
            {
                return true;
            }
            return left.Equals(right);
        }

        public static bool operator !=(PacketFileCheck left, PacketFileCheck right) => !(left == right);
    }
}